package com.alex;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.anythink.china.api.CustomAdapterDownloadListener;
import com.anythink.core.api.ATCustomVideo;
import com.anythink.nativead.api.ATNativePrepareExInfo;
import com.anythink.nativead.api.ATNativePrepareInfo;
import com.anythink.nativead.api.NativeAdInteractionType;
import com.anythink.nativead.unitgroup.api.CustomNativeAd;
import com.bytedance.sdk.openadsdk.ComplianceInfo;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdDislike;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTDrawFeedAd;
import com.bytedance.sdk.openadsdk.TTFeedAd;
import com.bytedance.sdk.openadsdk.TTImage;
import com.bytedance.sdk.openadsdk.TTNativeAd;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationViewBinder;

import java.util.ArrayList;
import java.util.List;

public class AlexGromoreNativeAd extends CustomNativeAd {
    final String TAG = getClass().getSimpleName();
    TTFeedAd mTTFeedAd;
    Context mContext;
    boolean isDownloadStart = false;
    AlexGromoreCustomVideo ttatCustomVideo;

    int mediaViewId;

    public AlexGromoreNativeAd(Context context, TTFeedAd ttFeedAd, boolean canInterrupt,
                               Bitmap videoPlayBitmap, int videoPlaySize) {
        mContext = context.getApplicationContext();
        mTTFeedAd = ttFeedAd;

        mediaViewId = 9527;
        try {
            int tempMediaViewId = mContext.getResources()
                    .getIdentifier("alex_gromore_mediaview_id", "id",
                            mContext.getPackageName());
            if (tempMediaViewId != 0) {
                mediaViewId = tempMediaViewId;
            }
        } catch (Throwable e) {

        }

        setNetworkInfoMap(mTTFeedAd.getMediaExtraInfo());

        setAdData(canInterrupt, videoPlayBitmap, videoPlaySize);
    }

    double videoProgress;

    public void setAdData(boolean canInterrupt, Bitmap videoPlayBitmap, int videoPlaySize) {
        setTitle(mTTFeedAd.getTitle());
        setDescriptionText(mTTFeedAd.getDescription());
        setAdFrom(mTTFeedAd.getSource());
        setStarRating((double) mTTFeedAd.getAppScore());
        setAppCommentNum(mTTFeedAd.getAppCommentNum());

        TTImage icon = mTTFeedAd.getIcon();
        if (icon != null) {
            setIconImageUrl(icon.getImageUrl());
        }

        List<TTImage> imageList = mTTFeedAd.getImageList();
        ArrayList<String> imageStringList = new ArrayList<>();
        if (imageList != null && imageList.size() > 0) {
            for (int i = 0; i < imageList.size(); i++) {
                TTImage ttImage = imageList.get(i);
                if (ttImage != null) {
                    imageStringList.add(ttImage.getImageUrl());
                    if (i == 0) {
                        setMainImageUrl(ttImage.getImageUrl());
                        setMainImageWidth(ttImage.getWidth());
                        setMainImageHeight(ttImage.getHeight());
                    }
                }
            }
        }
        setImageUrlList(imageStringList);

        setCallToActionText(mTTFeedAd.getButtonText());
        if (mTTFeedAd instanceof TTDrawFeedAd) {
            TTFeedAd.CustomizeVideo customizeVideo = ((TTDrawFeedAd) mTTFeedAd).getCustomVideo();
            if (customizeVideo != null) {
                setVideoUrl(customizeVideo.getVideoUrl());
                ttatCustomVideo = new AlexGromoreCustomVideo(customizeVideo);
            }
            ((TTDrawFeedAd) mTTFeedAd).setCanInterruptVideoPlay(canInterrupt);
            if (videoPlayBitmap != null && videoPlaySize > 0) {
                ((TTDrawFeedAd) mTTFeedAd).setPauseIcon(videoPlayBitmap, videoPlaySize);
            }
        }

        ComplianceInfo complianceInfo = mTTFeedAd.getComplianceInfo();
        if (complianceInfo != null) {
            if (!TextUtils.isEmpty(complianceInfo.getAppName()) || !TextUtils.isEmpty(
                    complianceInfo.getAppVersion()) || !TextUtils.isEmpty(
                    complianceInfo.getDeveloperName()) || !TextUtils.isEmpty(
                    complianceInfo.getPrivacyUrl()) || !TextUtils.isEmpty(
                    complianceInfo.getPermissionUrl()) || !TextUtils.isEmpty(
                    complianceInfo.getFunctionDescUrl())) {
                setAdAppInfo(new AlexGromoreDownloadAppInfo(complianceInfo, mTTFeedAd.getAppSize()));
            }
        }

        int nativeAdInteractionType = NativeAdInteractionType.UNKNOW;
        if (mTTFeedAd.getInteractionType() == 4) {
            nativeAdInteractionType = NativeAdInteractionType.APP_DOWNLOAD_TYPE;
        }
        if (mTTFeedAd.getInteractionType() == 3) {
            nativeAdInteractionType = NativeAdInteractionType.DEEPLINK_TYPE;
        }
        if (mTTFeedAd.getInteractionType() == 2) {
            nativeAdInteractionType = NativeAdInteractionType.H5_TYPE;
        }
        setNativeInteractionType(nativeAdInteractionType);

        if (mTTFeedAd != null) {
            TTFeedAd.CustomizeVideo customizeVideo = ((TTFeedAd) mTTFeedAd).getCustomVideo();
            if (customizeVideo != null) {
                setVideoUrl(customizeVideo.getVideoUrl());
                ttatCustomVideo = new AlexGromoreCustomVideo(customizeVideo);
            }
            setVideoDuration(mTTFeedAd.getVideoDuration());
            mTTFeedAd.setVideoAdListener(new TTFeedAd.VideoAdListener() {
                @Override
                public void onVideoLoad(TTFeedAd ttFeedAd) {
                }

                @Override
                public void onVideoError(int i, int i1) {
                    notifyAdVideoVideoPlayFail("" + i, "" + i1);
                }

                @Override
                public void onVideoAdStartPlay(TTFeedAd ttFeedAd) {
                    notifyAdVideoStart();
                }

                @Override
                public void onVideoAdPaused(TTFeedAd ttFeedAd) {
                }

                @Override
                public void onVideoAdContinuePlay(TTFeedAd ttFeedAd) {
                }

                @Override
                public void onVideoAdComplete(TTFeedAd ttFeedAd) {
                    notifyAdVideoEnd();
                }

                @Override
                public void onProgressUpdate(long current, long duration) {
                    if (getVideoDuration() == 0) {
                        setVideoDuration(duration / 1000D);
                    }

                    videoProgress = current / 1000D;
                    notifyAdVideoPlayProgress((int) videoProgress);
                }
            });
        }

        mTTFeedAd.setDownloadListener(new TTAppDownloadListener() {
            @Override
            public void onIdle() {

            }

            @Override
            public void onDownloadActive(long totalBytes, long currBytes, String fileName,
                                         String appName) {
                if (!isDownloadStart) {
                    isDownloadStart = true;
                    if (mDownloadListener != null && mDownloadListener instanceof CustomAdapterDownloadListener) {
                        ((CustomAdapterDownloadListener) mDownloadListener).onDownloadStart(
                                totalBytes, currBytes, fileName, appName);
                    }
                } else {
                    if (mDownloadListener != null && mDownloadListener instanceof CustomAdapterDownloadListener) {
                        ((CustomAdapterDownloadListener) mDownloadListener).onDownloadUpdate(
                                totalBytes, currBytes, fileName, appName);
                    }
                }

            }

            @Override
            public void onDownloadPaused(long totalBytes, long currBytes, String fileName,
                                         String appName) {
                if (mDownloadListener != null && mDownloadListener instanceof CustomAdapterDownloadListener) {
                    ((CustomAdapterDownloadListener) mDownloadListener).onDownloadPause(totalBytes,
                            currBytes, fileName, appName);
                }
            }

            @Override
            public void onDownloadFailed(long totalBytes, long currBytes, String fileName,
                                         String appName) {
                if (mDownloadListener != null && mDownloadListener instanceof CustomAdapterDownloadListener) {
                    ((CustomAdapterDownloadListener) mDownloadListener).onDownloadFail(totalBytes,
                            currBytes, fileName, appName);
                }
            }

            @Override
            public void onDownloadFinished(long totalBytes, String fileName, String appName) {
                if (mDownloadListener != null && mDownloadListener instanceof CustomAdapterDownloadListener) {
                    ((CustomAdapterDownloadListener) mDownloadListener).onDownloadFinish(totalBytes,
                            fileName, appName);
                }
            }

            @Override
            public void onInstalled(String fileName, String appName) {
                if (mDownloadListener != null && mDownloadListener instanceof CustomAdapterDownloadListener) {
                    ((CustomAdapterDownloadListener) mDownloadListener).onInstalled(fileName,
                            appName);
                }
            }
        });

        switch (mTTFeedAd.getImageMode()) {
            case TTAdConstant.IMAGE_MODE_VIDEO:
            case TTAdConstant.IMAGE_MODE_VIDEO_VERTICAL:
                mAdSourceType = NativeAdConst.VIDEO_TYPE;
                break;

            case TTAdConstant.IMAGE_MODE_GROUP_IMG:
            case TTAdConstant.IMAGE_MODE_LARGE_IMG:
            case TTAdConstant.IMAGE_MODE_SMALL_IMG:
            case TTAdConstant.IMAGE_MODE_VERTICAL_IMG:
                mAdSourceType = NativeAdConst.IMAGE_TYPE;
                break;
        }

    }

    private void getChildView(List<View> childViews, View view) {
        if (view instanceof ViewGroup && view != mTTFeedAd.getAdView()) {
            ViewGroup viewGroup = (ViewGroup) view;
            for (int i = 0; i < viewGroup.getChildCount(); i++) {
                View child = viewGroup.getChildAt(i);
                getChildView(childViews, child);
            }
        } else {
            if (view != mTTFeedAd.getAdView()) {
                childViews.add(view);
            }
        }
    }

    @Override
    public void prepare(final View view, ATNativePrepareInfo nativePrepareInfo) {

        List<View> clickViewList = nativePrepareInfo.getClickViewList();

        if (clickViewList == null || clickViewList.size() == 0) {
            clickViewList = new ArrayList<>();
            getChildView(clickViewList, view);
        }

        if (view.getContext() instanceof Activity) {
            final AdInteractionListenerImpl adInteractionListener = new AdInteractionListenerImpl();
            Activity activity = (Activity) view.getContext();
            registerView(view, (Activity) view.getContext(), nativePrepareInfo);
        } else {
            Log.w(TAG, TAG + " prepare fail," + view.getClass()
                    .getSimpleName() + " context must be Activity");
        }
    }

    private void registerView(View view, Activity context, ATNativePrepareInfo nativePrepareInfo) {
        View closeView = nativePrepareInfo.getCloseView();
        //register dislike dialog
        if (mTTFeedAd.getMediationManager().hasDislike() && closeView != null) {
            final TTAdDislike ttAdDislike = mTTFeedAd.getDislikeDialog(context);
            closeView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ttAdDislike.setDislikeInteractionCallback(
                            new TTAdDislike.DislikeInteractionCallback() {
                                @Override
                                public void onShow() {

                                }

                                @Override
                                public void onSelected(int i, String s, boolean b) {
                                    notifyAdDislikeClick();
                                }

                                @Override
                                public void onCancel() {

                                }
                            });

                    ttAdDislike.showDislikeDialog();
                }
            });
        }

        List<View> clickViewList = new ArrayList<>();

        List<View> clickViewLists = nativePrepareInfo.getClickViewList();
        if (clickViewLists != null && clickViewLists.size() > 0) {
            clickViewList.addAll(clickViewLists);
        } else {
            getChildView(clickViewList, view);
        }

        List<View> creativeViewList = new ArrayList<>();
        if (nativePrepareInfo instanceof ATNativePrepareExInfo) {
            List<View> creativeClickViewList = ((ATNativePrepareExInfo) nativePrepareInfo).getCreativeClickViewList();
            if (creativeClickViewList != null) {
                creativeViewList.addAll(creativeClickViewList);
            }
        }

        View parentView = nativePrepareInfo.getParentView();
        View titleView = nativePrepareInfo.getTitleView();
        View descView = nativePrepareInfo.getDescView();
        View ctaView = nativePrepareInfo.getCtaView();
        View adLogoView = nativePrepareInfo.getAdLogoView();
        View iconView = nativePrepareInfo.getIconView();
        View adFromView = nativePrepareInfo.getAdFromView();

        MediationViewBinder.Builder builder = new MediationViewBinder.Builder(
                parentView != null ? parentView.getId() : 0).titleId(
                        titleView != null ? titleView.getId() : 0)
                .sourceId(adFromView != null ? adFromView.getId() : 0)
                .descriptionTextId(descView != null ? descView.getId() : 0)
                .callToActionId(ctaView != null ? ctaView.getId() : 0)
                .logoLayoutId(adLogoView != null ? adLogoView.getId() : 0)
                .iconImageId(iconView != null ? iconView.getId() : 0);
        if (this.mediaViewId != 0) {
            builder.mediaViewIdId(this.mediaViewId);
        }

        try {
            mTTFeedAd.registerViewForInteraction(context, (ViewGroup) view, clickViewList,
                    creativeViewList, null, new AdInteractionListenerImpl(), builder.build());
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    @Override
    public Bitmap getAdLogo() {
        try {
            if (mTTFeedAd != null) {
                return mTTFeedAd.getAdLogo();
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void clear(final View view) {
        unregisterView(view);
    }

    private void unregisterView(View view) {
        if (view == null) {
            return;
        }
        if (view instanceof ViewGroup) {
            if (mTTFeedAd != null && view == mTTFeedAd.getAdView()) {
                return;
            }
            ViewGroup viewGroup = (ViewGroup) view;
            for (int i = 0; i < viewGroup.getChildCount(); i++) {
                View child = viewGroup.getChildAt(i);
                unregisterView(child);
            }
        } else {
            view.setOnClickListener(null);
            view.setClickable(false);
        }
    }


    View mMediaView;

    @Override
    public View getAdMediaView(Object... objeact) {
        if (mTTFeedAd.getImageMode() == TTAdConstant.IMAGE_MODE_VIDEO || mTTFeedAd.getImageMode() == TTAdConstant.IMAGE_MODE_VIDEO_VERTICAL) {
            if (mMediaView == null) {
                mMediaView = new FrameLayout(mContext);
                //((FrameLayout)mMediaView)
                mMediaView.setId(this.mediaViewId);
            }
            return mMediaView;
        }
        return mMediaView;
    }


    @Override
    public double getVideoProgress() {
        return videoProgress;
    }

    @Override
    public ATCustomVideo getNativeCustomVideo() {
        return ttatCustomVideo;
    }

    @Override
    public void destroy() {
        try {
            if (mTTFeedAd != null) {
                mTTFeedAd.setActivityForDownloadApp(null);
                mTTFeedAd.destroy();
            }
        } catch (Exception e) {

        }
        mContext = null;
        mTTFeedAd = null;
    }

    private class AdInteractionListenerImpl implements TTNativeAd.AdInteractionListener {
        @Override
        public void onAdClicked(View view, TTNativeAd ttNativeAd) {
            notifyAdClicked();
        }

        @Override
        public void onAdCreativeClick(View view, TTNativeAd ttNativeAd) {
            notifyAdClicked();
        }

        @Override
        public void onAdShow(TTNativeAd ttNativeAd) {
            setNetworkInfoMap(AlexGromoreConst.getNetworkMap(mTTFeedAd));
            notifyAdImpression();
        }
    }
}
